import { ElButton, ElDropdown, ElDropdownMenu, ElDropdownItem, ElIcon } from 'element-plus'
import { ArrowDown, Plus, Connection, Delete } from '@element-plus/icons-vue'
import { defineComponent } from 'vue'
import { hasPermission } from '@/modules/common/utils/Permission.util'

export default defineComponent({
  name: 'TableActions',
  props: {
    rowData: {
      type: Object,
      required: true
    },
    onDetail: Function,
    onAdd: Function,
    onEdit: Function,
    onChangeParent: Function,
    onDelete: Function,
    onDeleteConfirm: Function
  },
  setup(props) {
    const handleCommand = (command) => {
      const commandMap = {
        add: () => props.onAdd?.(props.rowData),
        changeParent: () => props.onChangeParent?.(props.rowData),
        delete: () => props.onDeleteConfirm?.(props.rowData)
      }
      commandMap[command]?.()
    }

    return () => (
      <div class="table-actions">
        {hasPermission(['SYSTEM:BASIC_DATA:AREA:DETAIL']) && (
          <ElButton size="small" onClick={() => props.onDetail?.(props.rowData)}>
            详情
          </ElButton>
        )}

        {hasPermission(['SYSTEM:BASIC_DATA:AREA:UPDATE']) && (
          <ElButton size="small" type="primary" onClick={() => props.onEdit?.(props.rowData)}>
            编辑
          </ElButton>
        )}

        <ElDropdown trigger="click" onCommand={handleCommand} placement="bottom-end">
          {{
            default: () => (
              <ElButton size="small" type="info">
                更多
                <ElIcon class="el-icon--right">
                  <ArrowDown />
                </ElIcon>
              </ElButton>
            ),
            dropdown: () => (
              <ElDropdownMenu>
                {hasPermission(['SYSTEM:BASIC_DATA:AREA:CREATE']) && (
                  <ElDropdownItem command="add">
                    <ElIcon><Plus /></ElIcon>
                    <span>新增</span>
                  </ElDropdownItem>
                )}
                {hasPermission(['SYSTEM:BASIC_DATA:AREA:UPDATE_PARENT']) && (
                  <ElDropdownItem command="changeParent">
                    <ElIcon><Connection /></ElIcon>
                    <span>修改父节点</span>
                  </ElDropdownItem>
                )}
                {hasPermission(['SYSTEM:BASIC_DATA:AREA:DELETE']) && (
                  <ElDropdownItem command="delete" divided>
                    <ElIcon><Delete /></ElIcon>
                    <span>删除</span>
                  </ElDropdownItem>
                )}
              </ElDropdownMenu>
            )
          }}
        </ElDropdown>
      </div>
    )
  }
})